package stack;

/** 用栈实现计算器 */
public class Calculator {
  public static void main(String[] args) {
    ArrayStack2 numStack = new ArrayStack2(10);
    ArrayStack2 operStack = new ArrayStack2(10);
    //String str="3+2*6-2";
    String str = "7-2*6+2";
    int index=0;
    int num1=0;
    int num2=0;
    int res=0;
    int oper=0;
    char ch=' ';
    //依次扫描字符串
    while(true){
      ch=str.substring(index,index+1).charAt(0);
      if (!operStack.isOpeartion(ch)){
        numStack.push(ch-'0');
      }else {
        if (!operStack.isEmpty()){
          if (operStack.pripority(ch)>=operStack.pripority(operStack.seek())){
            operStack.push(ch);
          }else{
            num1=numStack.pop();
            num2=numStack.pop();
            oper=operStack.pop();
            res=numStack.calculat(num1,num2,oper);
            numStack.push(res);
            operStack.push(ch);
          }
        }else {
          operStack.push(ch);
        }
      }
      index++;
      if (index>=str.length()){
        break;
      }
    }
    //数符全部入栈，pop出数符运算
    while(true){
      //符号栈空，则数栈为最终结果
      if (operStack.isEmpty()){
        break;
      }else {
        num1=numStack.pop();
        num2=numStack.pop();
        oper=operStack.pop();
        res=numStack.calculat(num1,num2,oper);
        numStack.push(res);
      }
    }
    System.out.println("结果为"+numStack.seek());
  }
}

class ArrayStack2 {
  int maxSize;
  int top = -1;
  int[] array;

  public ArrayStack2(int maxSize) {
    this.maxSize = maxSize;
    this.array = new int[maxSize];
  }

  // 栈空
  public boolean isEmpty() {
    return top == -1;
  }
  // 栈满
  public boolean isFull() {
    return top == maxSize - 1;
  }
  // 入栈
  public void push(int value) {
    if (isFull()) {
      System.out.println("栈满");
      return;
    }
    top++;
    array[top] = value;
  }

  // 出栈

  public int pop() {
    if (isEmpty()) {
      System.out.println("栈空");
      return -1;
    }
    int result= array[top];
    //System.out.printf("array[%d]=%d出栈", top, array[top]);
    top--;
    return result;
  }
  //查看栈顶元素
  public int seek(){
    return array[top];
  }
  //判断符号优先级
  public int pripority(int operation) {
    if (operation=='*'||operation=='/'){
      return 1;
    }else if (operation=='+'||operation=='-'){
      return 0;
    }else {
      return -1;
    }
  }

  //判断是否为运算符
  public boolean isOpeartion(char operation) {
    return operation=='+'||operation=='-'||operation=='*'||operation=='/';
  }

  //计算
  public int calculat(int num1,int num2,int operation){
    int result=0;
    switch (operation){
      case '+':
        result=num2+num1;
        break;
      case '-':
        result=num2-num1;
        break;
      case '*':
        result=num2*num1;
        break;
      case '/':
        result=num2/num1;
        break;
      default:
        break;
    }
    return result;
  }
}
